import bcrypt from 'bcryptjs';
// var express = require('express');
import express from 'express';
import jwt from 'jsonwebtoken';
import svgCaptcha from 'svg-captcha';

import { SYSTEM } from '../../config/Config';
import UserService from '../../service/system/UserService';
import BaseController from '../BaseController';

/**
 * 登陆接口
 */
export class LoginController extends BaseController<null> {
    /**
     * 用户服务
     */
    useService: UserService;
    constructor() {
        super();
        this.useService = new UserService();
    }
    /**
     * 生成验证码
     */
    captcha(req: express.Request, res: express.Response, next: express.NextFunction) {
        var captcha = svgCaptcha.create();
        req.session.captcha = captcha.text;
        req.session.captchaData = new Date().getTime();
        res.type('svg');
        res.status(200).send(captcha.data);
    }
    /**
     * 登陆操作
     */
    async login(req: express.Request, res: express.Response, next: express.NextFunction) {
        /**
         * 1.检测参数是否合法，账号、密码、验证码等不能为空
         * 2.校验验证码是否合法：验证码是否正确、验证码是否过期
         * 3.账号密码是否合法的校验
         */
        let captcha = req.body.captcha;
        let account = req.body.account;
        let password = req.body.password;
        if (!captcha || !account || !password) {
            res.status(400).send({
                code: 400,
                msg: '参数为空'
            })
            return;
        }
        //验证码合法性的判断"wBxqQKlIOWlecyawht2W7dJTCI9DD_qC"
        let systemCaptcha = req.session.captcha;
        let systemCaptchaDate = req.session.captchaData;
        if (!systemCaptcha || !systemCaptchaDate) {
            res.status(500).send({
                code: 500,
                msg: '验证码不合法'
            })
            return;
        }
        if (systemCaptcha !== captcha) {
            res.status(500).send({
                code: 500,
                msg: '验证码错误'
            })
            return;
        }
        if (new Date().getTime() - systemCaptchaDate > SYSTEM.captchaTimeOut) {
            res.status(500).send({
                code: 500,
                msg: '验证码已失效'
            })
            return;
        }
        //账号密码合法性的判断
        let systemUser = await this.useService.findByAccount(account).catch(error => {
            console.error(error);
            res.status(503).send({
                code: 503,
                msg: '系统错误：' + error.message
            })
        });
        if (!systemUser) {
            res.status(500).send({
                code: 500,
                msg: '账号错误'
            })
            return;
        }
        if (!bcrypt.compareSync(password, systemUser.password)) {//TODO 需进行加密判断
            res.status(500).send({
                code: 500,
                msg: '密码错误'
            })
            return;
        }
        //生成token，并且返回登陆成功信息
        let token = jwt.sign({
            id: systemUser.id,
            name: systemUser.name
        }, SYSTEM.privateKey, {
            expiresIn: '1d' // 1天 
        });
        res.header("authorization", token);
        res.send({
            code: 200,
            msg: ''
        })
    }
}

var router = express.Router();
const loginController = new LoginController();

//登陆接口
router.post('/login', loginController.login.bind(loginController));

//获取验证码
router.get('/login/captcha', loginController.captcha.bind(loginController));
// module.exports = router;
export default router;
